package com.seed.dev.web.user;

import cn.hutool.core.lang.UUID;
import com.seed.core.enumeration.YesNo;
import com.seed.application.service.BaseService;
import com.seed.uaa.util.EncryptUtil;
import org.springframework.stereotype.Service;

import static com.seed.dev.web.user.table.UserTableDef.USER;

@Service
public class UserService extends BaseService<UserMapper, User> {

    public UserService() {
        super(User.class);
    }

    public User getByUsername(String username) {
        return getMapper().selectOneByQuery(query().where(USER.USERNAME.eq(username)));
    }

    public boolean regist(User registUser) {
        String username = registUser.getUsername();
        String password = registUser.getPassword();
        User user = getByUsername(username);
        if(user != null) throw new RuntimeException(String.format("用户【%s】已存在", username));

        String salt = UUID.fastUUID().toString();
        String encrypt = EncryptUtil.encrypt(password, salt);
        user = new User();
        user.setUsername(username);
        user.setPassword(encrypt);
        user.setSalt(salt);
        user.setName(registUser.getName());
        user.setActive(YesNo.yes);
        user.setEnable(YesNo.yes);

        return getMapper().insert(user) > 0;
    }
}
